package com.expense.app.admin.resolvers;

import com.expense.app.admin.annotation.LoginUser;
import com.expense.app.admin.annotation.LoginUser;
import com.expense.common.model.auth.AdminUser;
import com.expense.common.util.UserUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 * @author liuBin
 */
@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return  parameter.getParameterType().isAssignableFrom(AdminUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID

        Object object = UserUtils.getUser();
        if(object == null){
            return null;
        }
//        if(templeUserServ == null) {
//            BeanFactory beanFactory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.ge);
//            templeUserServ = (TempleUserServ) beanFactory.getBean("templeUserServ");
//        }
        //获取用户信息
        AdminUser user = (AdminUser) object;

        return user;
    }
}
